package com.wedimob.slideshare.task.cpu;

import org.jsoup.nodes.Document;

import com.wedimob.slideshare.Factory;
import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.bo.Author;
import com.wedimob.slideshare.bo.Authors;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.io.disk.TaskAuthorWriter;
import com.wedimob.slideshare.task.io.network.TaskMediumWriter;

public class TaskAuthorsExtractor extends Task<Document, Authors> {

    private WriteType write;

    public TaskAuthorsExtractor(PoolExecutor pool, Document input, WriteType write, int limit,
            int timeout) {
        super(pool, input, timeout, timeout);
        this.write = write;
    }

    @Override
    public void run() {
        try {
            output = Factory.fromDocument(input, Authors.class, null);

            for (Author author : output) {
                pool.getResults().putResult(author);
                if (write != WriteType.NONE) {
                    pool.execAsync(new TaskMediumWriter(pool, author.getPicture(), timeout));
                    pool.execAsync(new TaskAuthorWriter(pool, author, timeout));
                }

                if (limit > 0 && pool.getResults().getNbResultType(Author.class) >= limit) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }
}
